<template>
  <view class="container page-with-cunba-nav">
    <!-- 自定义导航栏 -->
    <house-nav-bar 
      @nav-height="onNavHeightChange" 
      @city-changed="onCityChanged" 
      @go-back="handleBack"
    />
    
    <!-- 顶部轮播图横幅 -->
    <view class="header-banner-swiper">
      

      
      <!-- 轮播图 -->
      <swiper 
        class="banner-swiper"
        :indicator-dots="true"
        :autoplay="true"
        :interval="4000"
        :duration="500"
        :circular="true"
        indicator-color="rgba(255,255,255,0.5)"
        indicator-active-color="#fff"
        @change="onBannerChange"
      >
        <swiper-item v-for="(banner, index) in bannerList" :key="index" class="swiper-item">
          <view class="banner-slide" :style="{ backgroundImage: `url(${banner.image})` }" @click="onBannerClick(banner)">
            <!-- 渐变遮罩 -->
            <view class="banner-overlay"></view>
            
            <!-- 内容区域 -->
            <view class="banner-content">
              <view class="banner-title">{{ banner.title }}</view>
              <view class="banner-subtitle">{{ banner.subtitle }}</view>
              <view v-if="banner.description" class="banner-description">{{ banner.description }}</view>
            </view>
            
            <!-- 装饰元素 -->
            <view class="decoration-left" v-if="banner.showDecorations">
              <image class="basketball-icon" src="/static/images/basketball.png" mode="aspectFit"></image>
            </view>
            <view class="decoration-right" v-if="banner.showDecorations">
              <image class="player-icon" src="/static/images/player.png" mode="aspectFit"></image>
            </view>
          </view>
        </swiper-item>
      </swiper>
    </view>

    <!-- 近期赛事 -->
    <view class="section match-section">
      <view class="section-header">
        <view class="section-title">近期赛事</view>
        <view class="section-more" @click="viewAllMatches">全部赛程 ></view>
      </view>
      
      <!-- 横向滚动赛事列表组件 -->
      <match-scroll-list 
        :matches="displayMatches"
        :loading="loading.matches"
        @match-click="viewMatchDetail"
        @reservation-click="goToReservation"
      />
    </view>

    <!-- 球队排名 -->
    <view class="section">
      <view class="section-header">
        <view class="section-title">球队排名</view>
        <view class="section-more" @click="viewRanking">完整排行榜 ></view>
      </view>
      
              <!-- 动态分组标签 -->
        <view class="ranking-tabs" v-if="groupList.length > 0">
          <view 
            class="tab-item" 
            v-for="(group, index) in groupList" 
            :key="group.id"
            :class="{ active: activeGroupIndex === index }" 
            @click="switchTab(index)"
          >
            {{ group.name }}
          </view>
        </view>
      
      <!-- 默认标签（当没有分组数据时） -->
      <view class="ranking-tabs" v-else>
        <view class="tab-item active">
          数据加载中...
        </view>
      </view>
      
      <!-- 使用RankingTable组件 -->
      <RankingTable 
        :teamList="currentRankings"
        :loading="loading.rankings && activeTab === 0"
        emptyText="暂无排名数据"
        emptyTips="请稍后再试"
        @team-click="goToTeamDetail"
      />
    </view>

    <!-- 自定义导航栏 -->
    <cunba-nav-bar :activeIndex="0" :badges="navBadges" @nav-change="onNavChange"></cunba-nav-bar>
  </view>
</template>

<script>
import CunbaNavBar from '@/components/cunba-nav-bar/index.vue'
import HouseNavBar from '@/components/house_nav/index.vue'
import MatchScrollList from '@/components/matchScrollList/index.vue'
import RankingTable from '@/components/cunba/RankingTable/index.vue'
// import MatchSwiper from '@/components/matchSwiper/index.vue'
import { 
  getEventList, 
  getMatchList, 
  getTeamRanking, 
  getCalendarData,
  formatMatchData, 
  formatTeamData 
} from '@/api/cunba.js'
import { getDiy } from '@/api/api.js'

export default {
  components: {
    CunbaNavBar,
    HouseNavBar,
    MatchScrollList,
    RankingTable
  },
  data() {
    return {
      activeTab: 0,
      isPageScrolled: false, // 页面滚动状态，用于改变定位组件样式

      // 加载状态
      loading: {
        events: false,
        matches: false,
        rankings: false
      },
      // 导航栏角标配置
      navBadges: {
        home: 0,     // 首页角标
        schedule: 0, // 赛程角标
        team: 0,     // 球队角标
        mine: 1      // 我的角标
      },
      // 排名相关数据
      groupList: [],        // 动态分组列表
      rankingData: [],      // 完整排名数据
      currentGroupTeams: [], // 当前组别的球队数据（参考排行榜页面）
      activeGroupIndex: 0,  // 当前选中的组别索引（参考排行榜页面）
      currentEventId: null, // 当前赛事ID
      // 顶部轮播图数据
      bannerList: [
        {
          id: 1,
          title: '村BA篮球赛',
          subtitle: '激情碰撞 精彩无限',
          description: '感受最纯粹的篮球魅力',
          image: 'https://cdn.zhzfpn.cn/PicGo/20250829202251655.png',
          showDecorations: true,
          link: ''
        },
        {
          id: 2,
          title: '村BA篮球赛',
          subtitle: '激情碰撞 精彩无限',
          description: '感受最纯粹的篮球魅力',
          image: 'https://cdn.zhzfpn.cn/PicGo/20250829202251655.png',
          showDecorations: true,
          link: ''
        },
        {
          id: 3,
          title: '村BA篮球赛',
          subtitle: '激情碰撞 精彩无限',
          description: '感受最纯粹的篮球魅力',
          image: 'https://cdn.zhzfpn.cn/PicGo/20250829202251655.png',
          showDecorations: false,
          link: ''
        }
      ],
      // API数据
      eventList: [],       // 赛事列表
      recentMatches: [],   // 近期比赛（从API获取）
      rankings: [],        // 球队排名数据（从API获取）

    }
  },
  computed: {
    // 当前选中的组别信息（参考排行榜页面）
    currentGroup() {
      return this.groupList[this.activeGroupIndex] || null
    },
    

    
    // 当前标签页的排名数据
    currentRankings() {
      // 过滤掉无效数据
      const validTeams = this.currentGroupTeams.filter(team => {
        return team && typeof team === 'object'
      })
      
      return validTeams
    },
    // 是否正在加载
    isLoading() {
      return this.loading.events || this.loading.matches || this.loading.rankings
    },
    // 显示的比赛数据（只使用API数据）
    displayMatches() {
      console.log('📊 === displayMatches计算 ===')
      console.log('📋 API数据数量:', this.recentMatches.length)
      
      // 详细检查每场比赛的球队信息
      this.recentMatches.forEach((match, index) => {
        console.log(`🏀 比赛${index + 1}:`, {
          id: match.id,
          homeTeam: match.homeTeam,
          awayTeam: match.awayTeam,
          time: match.time,
          timeLabel: match.timeLabel
        })
      })
      
      return this.recentMatches
    },
    // 轮播图显示的比赛数据
    swiperMatches() {
      return this.displayMatches
    },
    // 显示的城市名称 - 从store获取
    displayCityName() {
      const location = this.$store.state.location || this.$store.getters.getLocation;
      if (location) {
        return location.address || location.city || location.province || '六盘水市';
      }
      return '六盘水市';
    }
  },
  onLoad() {
    console.log('赛事首页加载完成')
    // 生成今天和明天的默认比赛数据
    this.generateTodayTomorrowMatches()
    this.initData()
    // 启动模拟数据更新（演示角标功能）
    this.simulateDataUpdate()
    // 使用bannerList中的固定村BA轮播图数据
  },
  
    onShow() {
    console.log('页面显示')
    // 使用bannerList中的固定村BA轮播图数据，无需重置
  },

  /**
   * 处理导航栏返回按钮点击事件
   */
  onNavigationBarButtonTap() {
    uni.navigateBack({
      delta: 1
    })
  },
  methods: {
    // 导航栏高度变化事件
    onNavHeightChange(height) {
      this.navBarHeight = height;
    },
    
    // 城市切换事件
    onCityChanged(data) {
      console.log('城市已切换:', data);
      // 可以在这里重新加载相关数据
      // this.initData();
    },
    
    // 返回按钮点击事件
    handleBack() {
      console.log('村BA首页返回按钮点击');
      // HouseNavBar组件已经处理了返回逻辑，这里不需要额外处理
    },
    
    // 生成今天和明天的默认比赛数据
    generateTodayTomorrowMatches() {
      const today = new Date()
      const tomorrow = new Date(today)
      tomorrow.setDate(today.getDate() + 1)
      
      // 格式化日期为字符串
      const formatDate = (date) => {
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        return `${year}-${month}-${day}`
      }
      
      const todayStr = formatDate(today)
      const tomorrowStr = formatDate(tomorrow)
      
      this.defaultMatches = [
        // 今天的比赛
        {
          id: 1,
          time: '14:30',
          matchTime: `${todayStr} 14:30:00`,
          homeTeam: {
            id: 1,
            name: '黔西村队',
            logo: '/static/images/team.png'
          },
          awayTeam: {
            id: 2,
            name: '安顺村队',
            logo: '/static/images/team.png'
          },
          venue: '村BA球馆',
          city: '贵阳市',
          status: {
            code: 'upcoming',
            text: '未开始',
            statusClass: 'status-upcoming'
          },
          watchInfo: {
            type: 'free',
            text: '免费观',
            needReservation: false,
            price: 0,
            watchBtnClass: 'btn-free'
          }
        },
        {
          id: 2,
          time: '19:00',
          matchTime: `${todayStr} 19:00:00`,
          homeTeam: {
            id: 3,
            name: '毕节村队',
            logo: '/static/images/team.png'
          },
          awayTeam: {
            id: 4,
            name: '凯里苗族队',
            logo: '/static/images/team.png'
          },
          venue: '村BA球馆',
          city: '贵阳市',
          status: {
            code: 'live',
            text: '进行中',
            statusClass: 'status-live'
          },
          watchInfo: {
            type: 'free',
            text: '免费观',
            needReservation: false,
            price: 0,
            watchBtnClass: 'btn-free'
          }
        },
        // 明天的比赛
        {
          id: 3,
          time: '10:00',
          matchTime: `${tomorrowStr} 10:00:00`,
          homeTeam: {
            id: 5,
            name: '福泉山水队',
            logo: '/static/images/team.png'
          },
          awayTeam: {
            id: 6,
            name: '都匀绿茶队',
            logo: '/static/images/team.png'
          },
          venue: '村BA球馆',
          city: '贵阳市',
          status: {
            code: 'upcoming',
            text: '未开始',
            statusClass: 'status-upcoming'
          },
          watchInfo: {
            type: 'reservation',
            text: '预约',
            needReservation: true,
            price: 0,
            watchBtnClass: 'btn-reserve'
          }
        },
        {
          id: 4,
          time: '15:30',
          matchTime: `${tomorrowStr} 15:30:00`,
          homeTeam: {
            id: 7,
            name: '兴义布依队',
            logo: '/static/images/team.png'
          },
          awayTeam: {
            id: 8,
            name: '兴仁布依族队',
            logo: '/static/images/team.png'
          },
          venue: '村BA球馆',
          city: '贵阳市',
          status: {
            code: 'upcoming',
            text: '未开始',
            statusClass: 'status-upcoming'
          },
          watchInfo: {
            type: 'free',
            text: '免费观',
            needReservation: false,
            price: 0,
            watchBtnClass: 'btn-free'
          }
        }
      ]
      
      console.log('🎯 === 生成今天和明天的比赛数据 ===')
      console.log('📅 今天日期:', todayStr)
      console.log('📅 明天日期:', tomorrowStr)
      console.log('📊 生成的比赛数量:', this.defaultMatches.length)
      console.log('📋 生成的比赛详情:', this.defaultMatches.map(m => ({
        id: m.id,
        time: m.time,
        matchTime: m.matchTime,
        teams: `${m.homeTeam.name} VS ${m.awayTeam.name}`,
        status: m.status.text
      })))
    },
    
    // 切换排名标签（完全参考排行榜页面）
    switchTab(index) {
      console.log('切换排名标签到:', index)
      this.activeGroupIndex = index  // 使用activeGroupIndex而不是activeTab
      
      // 如果有动态分组数据，筛选对应的球队数据（参考排行榜页面）
      const selectedGroup = this.groupList[index]
      if (selectedGroup) {
        console.log('选中分组:', selectedGroup.name, '索引:', index)
        
        // 切换组别时筛选对应的球队数据（参考排行榜页面）
        this.filterGroupData(selectedGroup)
      }
    },
    
    // 初始化数据
    async initData() {
      console.log('初始化赛事数据')
      try {
        // 先获取赛事列表，然后并行获取其他数据
        await this.loadEventList()
        
        // 统一使用赛事ID为2
        this.currentEventId = 2
        console.log('统一设置赛事ID为2:', this.currentEventId)
        
        // 并行获取其他数据（移除轮播图API调用，使用固定的村BA轮播图数据）
        await Promise.all([
          // this.loadHomeBannerData(), // 已移除API轮播图调用，使用bannerList中的村BA数据
          this.loadRecentMatches(),
          this.loadTeamRankings()
        ])
        console.log('数据加载完成')
      } catch (error) {
        console.error('数据加载失败:', error)
        uni.showToast({
          title: '数据加载失败，显示默认数据',
          icon: 'none'
        })
      }
    },
    
    // 加载首页轮播图数据
    async loadHomeBannerData() {
      try {
        console.log('=== 开始获取首页轮播图数据 ===')
        console.log('调用getDiy API参数:', { id: 0, version: '221' })
        
        const result = await getDiy({ id: 0, version: '221' })
        console.log('=== getDiy API响应 ===')
        console.log('响应状态:', result?.status || result?.code)
        console.log('响应消息:', result?.message || result?.msg)
        console.log('完整响应数据:', JSON.stringify(result, null, 2))
        
        if (result && result.data && result.data.value) {
          console.log('=== 解析轮播图数据 ===')
          const styleConfig = result.data.value
          console.log('styleConfig键列表:', Object.keys(styleConfig))
          
          let swiperData = null
          let foundSwiperConfig = false
          
          // 遍历配置查找swiperBg组件
          Object.keys(styleConfig).forEach(key => {
            const item = styleConfig[key]
            console.log(`检查配置项 ${key}:`, {
              name: item.name,
              hasSwiperConfig: !!item.swiperConfig,
              hasConfigList: !!(item.swiperConfig && item.swiperConfig.list),
              listLength: item.swiperConfig?.list?.length || 0
            })
            
            if (item.name === 'swiperBg') {
              foundSwiperConfig = true
              console.log('找到swiperBg组件:', item)
              if (item.swiperConfig && item.swiperConfig.list) {
                swiperData = item.swiperConfig.list
                console.log('提取轮播图数据:', swiperData)
              }
            }
          })
          
          if (!foundSwiperConfig) {
            console.warn('=== 未找到swiperBg组件 ===')
            console.log('可用组件列表:', Object.keys(styleConfig).map(key => ({
              key,
              name: styleConfig[key].name,
              type: typeof styleConfig[key]
            })))
          }
          
          if (swiperData && swiperData.length > 0) {
            console.log('=== 转换轮播图数据 ===')
            console.log('原始轮播图数据:', swiperData)
            
            // 转换数据格式为村BA轮播图格式
            const convertedData = swiperData.map((item, index) => {
              const converted = {
                id: index + 1,
                title: item.title || '',
                subtitle: item.subtitle || '',
                description: item.describe || '',
                image: this.setDomain(item.img),
                showDecorations: index < 2,
                link: item.info && item.info[1] ? item.info[1].value : ''
              }
              console.log(`转换第${index + 1}张轮播图:`, {
                原始: {
                  img: item.img,
                  title: item.title,
                  subtitle: item.subtitle,
                  describe: item.describe,
                  info: item.info
                },
                转换后: converted
              })
              return converted
            })
            
            this.bannerList = convertedData
            console.log('=== 轮播图数据更新成功 ===')
            console.log('最终bannerList:', this.bannerList)
            
            uni.showToast({
              title: `成功加载${swiperData.length}张轮播图`,
              icon: 'success',
              duration: 2000
            })
          } else {
            console.warn('=== 未找到有效轮播图数据 ===')
            console.log('swiperData:', swiperData)
            console.log('保持使用默认轮播图数据')
            uni.showToast({
              title: '未找到首页轮播图，使用默认数据',
              icon: 'none',
              duration: 2000
            })
          }
        } else {
          console.error('=== API响应数据格式异常 ===')
          console.log('result结构:', {
            hasResult: !!result,
            hasData: !!(result && result.data),
            hasValue: !!(result && result.data && result.data.value),
            resultKeys: result ? Object.keys(result) : [],
            dataKeys: result?.data ? Object.keys(result.data) : []
          })
        }
      } catch (error) {
        console.error('=== 获取首页轮播图数据失败 ===')
        console.error('错误类型:', error.constructor.name)
        console.error('错误信息:', error.message)
        console.error('错误堆栈:', error.stack)
        console.error('完整错误对象:', JSON.stringify(error, Object.getOwnPropertyNames(error)))
        
        uni.showToast({
          title: '轮播图数据加载失败，使用默认数据',
          icon: 'none',
          duration: 3000
        })
        
        console.log('当前默认轮播图数据:', this.bannerList)
      }
    },
    
    // 处理图片域名（参考首页swiperBg组件的方法）
    setDomain(url) {
      if (!url) return 'https://cdn.zhzfpn.cn/PicGo/20250829202251655.png' // 默认村BA轮播图
      url = url.toString()
      // 本地调试打开,生产请注销
      if (url.indexOf("https://") > -1) return url
      else return url.replace('http://', 'https://')
    },
    
    // 加载赛事列表
    async loadEventList() {
      this.loading.events = true
      try {
        console.log('开始请求赛事列表...')
        const result = await getEventList()
        console.log('赛事列表原始响应:', result)
        
        // 检查不同的响应格式
        if (result && result.data) {
          this.eventList = Array.isArray(result.data) ? result.data : [result.data]
          console.log('解析后的赛事列表:', this.eventList)
        } else if (result && Array.isArray(result)) {
          // 直接返回数组的情况
          this.eventList = result
        }
      } catch (error) {
        console.error('获取赛事列表失败:', error)
        console.error('错误详情:', JSON.stringify(error))
      } finally {
        this.loading.events = false
      }
    },
    
    // 加载近期比赛（使用日历接口获取今天和明天的比赛）
    async loadRecentMatches() {
      this.loading.matches = true
      try {
        console.log('🔍 === 开始获取今天和明天的比赛数据 ===')
        
        // 获取今天和明天的日期
        const today = new Date()
        const tomorrow = new Date(today)
        tomorrow.setDate(today.getDate() + 1)
        
        const formatDate = (date) => {
          const year = date.getFullYear()
          const month = String(date.getMonth() + 1).padStart(2, '0')
          const day = String(date.getDate()).padStart(2, '0')
          return `${year}-${month}-${day}`
        }
        
        const todayStr = formatDate(today)
        const tomorrowStr = formatDate(tomorrow)
        
        console.log('📅 今天日期:', todayStr)
        console.log('📅 明天日期:', tomorrowStr)
        
        // 并行请求今天和明天的比赛数据
        const [todayResult, tomorrowResult] = await Promise.all([
          getCalendarData({
            date: todayStr,
            matchType: 1,
            page: 1,
            limit: 20
          }),
          getCalendarData({
            date: tomorrowStr,
            matchType: 1,
            page: 1,
            limit: 20
          })
        ])
        
        console.log('📊 今天的比赛完整响应:', JSON.stringify(todayResult, null, 2))
        console.log('📊 明天的比赛完整响应:', JSON.stringify(tomorrowResult, null, 2))
        
        // 合并今天和明天的比赛数据
        let allMatches = []
        
        // 处理今天的比赛
        if (todayResult && todayResult.data) {
          let todayMatches = []
          if (Array.isArray(todayResult.data)) {
            todayMatches = todayResult.data
          } else if (todayResult.data.list && Array.isArray(todayResult.data.list)) {
            todayMatches = todayResult.data.list
          } else if (todayResult.data.matches && Array.isArray(todayResult.data.matches)) {
            todayMatches = todayResult.data.matches
          } else {
            todayMatches = [todayResult.data]
          }
          
          console.log('📋 今天的比赛列表:', todayMatches)
          
          allMatches = allMatches.concat(todayMatches.map(match => ({
            ...match,
            dateType: 'today',
            originalDate: todayStr
          })))
        }
        
        // 处理明天的比赛
        if (tomorrowResult && tomorrowResult.data) {
          let tomorrowMatches = []
          if (Array.isArray(tomorrowResult.data)) {
            tomorrowMatches = tomorrowResult.data
          } else if (tomorrowResult.data.list && Array.isArray(tomorrowResult.data.list)) {
            tomorrowMatches = tomorrowResult.data.list
          } else if (tomorrowResult.data.matches && Array.isArray(tomorrowResult.data.matches)) {
            tomorrowMatches = tomorrowResult.data.matches
          } else {
            tomorrowMatches = [tomorrowResult.data]
          }
          
          console.log('📋 明天的比赛列表:', tomorrowMatches)
          
          allMatches = allMatches.concat(tomorrowMatches.map(match => ({
            ...match,
            dateType: 'tomorrow',
            originalDate: tomorrowStr
          })))
        }
        
        console.log('🏀 合并后的比赛数据 (转换前):', allMatches)
        
        if (allMatches.length > 0) {
          // 转换数据格式
          this.recentMatches = allMatches.map(match => {
            console.log('🔄 转换单个比赛数据:', match)
            console.log('🏀 球队信息检查:', {
              team1_name: match.team1_name,
              team2_name: match.team2_name,
              home_team_name: match.home_team_name,
              away_team_name: match.away_team_name,
              homeTeamName: match.homeTeamName,
              awayTeamName: match.awayTeamName,
              homeTeam: match.homeTeam,
              awayTeam: match.awayTeam
            })
            const formatted = formatMatchData(match)
            console.log('✅ 转换结果:', formatted)
            console.log('🎯 球队名称结果:', {
              homeTeamName: formatted.homeTeam.name,
              awayTeamName: formatted.awayTeam.name
            })
            return formatted
          })
          console.log('✅ 最终转换后的比赛数据:', this.recentMatches)
          
          // 更新赛程角标
          this.updateNavBadge('schedule', this.recentMatches.length)
        } else {
          console.log('📭 今天和明天没有比赛数据，使用默认数据')
          this.recentMatches = []
        }
        
      } catch (error) {
        console.error('❌ 获取今天和明天的比赛失败:', error)
        console.error('错误详情:', JSON.stringify(error))
        // 使用默认数据
        this.recentMatches = []
      } finally {
        this.loading.matches = false
      }
    },
    
    // 加载球队排名（分别请求每个分组的数据）
    async loadTeamRankings() {
      this.loading.rankings = true
      console.log('=== 开始加载首页排名数据 ===')
      console.log('使用统一赛事ID: 2')
      
      // 清空之前的排名数据，避免重复
      this.rankingData = []
      this.groupList = []
      
      try {
        // 预定义的分组信息（根据实际API数据结构）
        const predefinedGroups = [
          { id: 13, name: "A组", eventId: 2, isSelected: true },
          { id: 14, name: "B组", eventId: 2, isSelected: false },
          { id: 15, name: "C组", eventId: 2, isSelected: false },
          { id: 16, name: "决赛", eventId: 2, isSelected: false }
        ]
        
        // 设置分组列表
        this.groupList = predefinedGroups
        this.activeGroupIndex = 0 // 默认选中A组（index=0）
        
        console.log('使用预定义分组列表:', this.groupList)
        
        // 使用排行榜页面相同的测试参数（关键修改！）
        const testParams = [
          { eventId: 2, groupId: 1, matchType: 'group' },
          { eventId: 2, groupId: 4, matchType: 'final' },
          { eventId: 2, groupId: 2, matchType: 'group' },
          { eventId: 2, groupId: 3, matchType: 'group' }
        ]
        
        for (let i = 0; i < testParams.length; i++) {
          const params = testParams[i]
          console.log(`\n--- 请求 ${i + 1}: 参数 ---`)
          console.log('请求参数:', params)
          
          try {
            const response = await getTeamRanking(params)
            console.log(`--- 请求 ${i + 1}: 响应成功 ---`)
            console.log('完整响应:', response)
            
            if (response && response.data) {
              // 只在第一次成功请求时设置数据（完全参考排行榜页面）
              if (i === 0) {
                // 更新排行榜数据
                if (response.data.rankings && response.data.rankings.length > 0) {
                  this.rankingData = response.data.rankings
                  console.log('--- 更新排行榜数据 ---')
                  console.log('排行榜数据:', this.rankingData)
                  console.log('排行榜数据长度:', this.rankingData.length)
                  
                  // 如果有组别数据，筛选默认组别的球队数据
                  if (this.groupList.length > 0) {
                    this.filterGroupData(this.groupList[this.activeGroupIndex])
                  }
                }
              }
              
              // 详细打印第一个队伍数据
              if (response.data.rankings && response.data.rankings.length > 0) {
                console.log('--- 第一个队伍详细信息 ---')
                console.log('队伍数据:', response.data.rankings[0])
              }
            }
          } catch (error) {
            console.log(`--- 请求 ${i + 1}: 请求失败 ---`)
            console.error('请求错误:', error)
          }
          
          // 延迟避免请求过快
          if (i < testParams.length - 1) {
            await new Promise(resolve => setTimeout(resolve, 1000))
          }
        }
        
        console.log('\n=== 排行榜数据加载完成 ===')
        
        // 更新球队角标
        if (this.rankingData.length > 0) {
          this.updateNavBadge('team', this.rankingData.length)
        }
        
      } catch (error) {
        console.error('加载排名数据失败:', error)
        console.error('错误详情:', JSON.stringify(error))
        // 保持默认数据
      } finally {
        this.loading.rankings = false
      }
    },
    
    // 查看比赛详情
    viewMatchDetail(match) {
      console.log('查看比赛详情', match)
      // 跳转到比赛详情页
      // uni.navigateTo({
      //   url: `/pages/cunba/match_detail/index?id=${match.id}`
      // })
    },
    
    // 跳转到预约页面，传递完整的比赛信息
    goToReservation(match) {
      console.log('=== 村BA首页跳转到预约页面 ===')
      console.log('比赛信息:', match)
      
      if (!match || !match.id) {
        uni.showToast({
          title: '比赛信息不完整',
          icon: 'none'
        })
        return
      }
      
      // 参考赛程表的实现方式：将比赛数据存储到全局状态
      const app = getApp()
      app.globalData = app.globalData || {}
      app.globalData.currentMatch = match
      
      console.log('已将比赛数据存储到全局状态:', match)
      
      // 同时构建URL参数作为备选方案（兼容性考虑）
      const params = {
        matchId: match.id,
        // 比赛基本信息
        matchTime: match.matchTime || match.time,
        venue: match.venue || '村BA球馆',
        city: match.city || '贵阳市',
        status: match.status?.text || match.status || '未开始',
        // 主队信息
        homeTeamId: match.homeTeam?.id || match.homeTeam?.teamId,
        homeTeamName: match.homeTeam?.name || match.homeTeam?.teamName || '主队',
        homeTeamLogo: match.homeTeam?.logo || match.homeTeam?.teamAvatar || '/static/images/team.png',
        homeScore: match.homeScore || match.homeTeam?.score || 0,
        // 客队信息
        awayTeamId: match.awayTeam?.id || match.awayTeam?.teamId,
        awayTeamName: match.awayTeam?.name || match.awayTeam?.teamName || '客队',
        awayTeamLogo: match.awayTeam?.logo || match.awayTeam?.teamAvatar || '/static/images/team.png',
        awayScore: match.awayScore || match.awayTeam?.score || 0
      }
      
      // 将参数转换为查询字符串
      const queryString = Object.keys(params)
        .filter(key => params[key] !== undefined && params[key] !== null)
        .map(key => `${key}=${encodeURIComponent(params[key])}`)
        .join('&')
      
      console.log('URL参数（备选方案）:', params)
      
      // 跳转到预约页面
      uni.navigateTo({
        url: `/pages/cunba/book/index?${queryString}`
      })
    },
    
    // 轮播图切换事件
    onSwiperChange(event) {
      console.log('轮播图切换:', event)
      // 可以在这里添加埋点统计等逻辑
    },
    
    // 查看全部赛程
    viewAllMatches() {
      uni.navigateTo({
        url: '/pages/cunba/calendar/index'
      })
    },
    
    // 格式化比赛日期
    formatMatchDate(dateTime) {
      if (!dateTime) return ''
      
      const date = new Date(dateTime)
      const today = new Date()
      const tomorrow = new Date(today)
      tomorrow.setDate(today.getDate() + 1)
      
      // 判断是今天、明天还是具体日期
      if (this.isSameDay(date, today)) {
        return '今天'
      } else if (this.isSameDay(date, tomorrow)) {
        return '明天'
      } else {
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        return `${month}月${day}日`
      }
    },
    
    // 判断是否为同一天
    isSameDay(date1, date2) {
      return date1.getFullYear() === date2.getFullYear() &&
             date1.getMonth() === date2.getMonth() &&
             date1.getDate() === date2.getDate()
    },
    
    // 筛选今天和明天的比赛
    filterTodayTomorrowMatches(matches) {
      if (!matches || matches.length === 0) {
        console.log('❌ 没有比赛数据需要筛选')
        return []
      }
      
      const today = new Date()
      const tomorrow = new Date(today)
      tomorrow.setDate(today.getDate() + 1)
      
      console.log('🔍 === 开始筛选今天和明天的比赛 ===')
      console.log('📅 今天:', today.toLocaleDateString())
      console.log('📅 明天:', tomorrow.toLocaleDateString())
      console.log('📋 原始比赛数据:', matches.map(m => ({
        id: m.id,
        name: `${m.homeTeam?.name} VS ${m.awayTeam?.name}`,
        matchTime: m.matchTime,
        venue: m.venue
      })))
      
      const todayTomorrowMatches = matches.filter(match => {
        // 尝试从不同的字段获取比赛时间
        const matchTime = match.matchTime || match.match_time || match.time || match.startTime || match.date
        if (!matchTime) {
          console.log('⚠️ 比赛缺少时间信息:', match)
          console.log('⚠️ 检查的字段:', {
            matchTime: match.matchTime,
            match_time: match.match_time, 
            time: match.time,
            startTime: match.startTime,
            date: match.date
          })
          return false
        }
        
        try {
          // 处理不同的日期格式
          let matchDate
          if (typeof matchTime === 'string') {
            // iOS兼容的日期解析
            const formattedDate = matchTime.replace(/-/g, '/')
            matchDate = new Date(formattedDate)
          } else {
            matchDate = new Date(matchTime)
          }
          
          // 检查日期是否有效
          if (isNaN(matchDate.getTime())) {
            console.warn('❌ 无效的比赛时间格式:', matchTime)
            return false
          }
          
          const isToday = this.isSameDay(matchDate, today)
          const isTomorrow = this.isSameDay(matchDate, tomorrow)
          
          console.log(`🏀 ${match.homeTeam?.name || match.team1_name || '队伍1'} VS ${match.awayTeam?.name || match.team2_name || '队伍2'}:`)
          console.log(`   原始时间: ${matchTime}`)
          console.log(`   解析后: ${matchDate.toLocaleDateString()} ${matchDate.toLocaleTimeString()}`)
          console.log(`   是今天: ${isToday}`)
          console.log(`   是明天: ${isTomorrow}`)
          console.log(`   保留: ${isToday || isTomorrow}`)
          
          // 判断是否为今天或明天
          return isToday || isTomorrow
        } catch (error) {
          console.error('❌ 解析比赛时间失败:', matchTime, error)
          return false
        }
      })
      
      // 按时间排序（今天的在前，明天的在后）
      const sortedMatches = todayTomorrowMatches.sort((a, b) => {
        try {
          const dateA = typeof a.matchTime === 'string' 
            ? new Date(a.matchTime.replace(/-/g, '/')) 
            : new Date(a.matchTime)
          const dateB = typeof b.matchTime === 'string' 
            ? new Date(b.matchTime.replace(/-/g, '/')) 
            : new Date(b.matchTime)
          return dateA - dateB
        } catch (error) {
          console.error('排序时解析日期失败:', error)
          return 0
        }
      })
      
      console.log('=== 筛选今天和明天的比赛 ===')
      console.log('原始比赛数量:', matches.length)
      console.log('筛选后比赛数量:', sortedMatches.length)
      console.log('今天和明天的比赛:', sortedMatches.map(m => ({
        name: `${m.homeTeam?.name} VS ${m.awayTeam?.name}`,
        time: m.matchTime,
        formatTime: this.formatMatchDate(m.matchTime)
      })))
      
      return sortedMatches
    },
    

    
    // 跳转到球队详情页面
    goToTeamDetail(team) {
      // 参数有效性检查
      if (!team || typeof team !== 'object') {
        team = { id: 3, name: 'BSK' }
      }
      
      try {
        const teamId = team.teamId || team.id || 3
        const teamName = team.teamName || team.name || 'BSK'
        const eventId = 2
        
        const url = `/pages/cunba/team_detail/index?teamId=${teamId}&teamName=${encodeURIComponent(teamName)}&eventId=${eventId}`
        
        uni.navigateTo({ 
          url,
          fail: (err) => {
            uni.showToast({
              title: '页面跳转失败，请重试',
              icon: 'error'
            })
          }
        })
      } catch (error) {
        uni.showToast({
          title: '操作失败，请重试',
          icon: 'error'
        })
      }
    },

    // 查看球员详情
    viewPlayerDetail() {
      uni.navigateTo({
        url: '/pages/cunba/player_detail/index?playerId=1'
      })
    },

    // 查看球员列表
    viewPlayerList() {
      uni.navigateTo({
        url: '/pages/cunba/player_list/index'
      })
    },

    // 查看完整排行榜
    viewRanking() {
      uni.navigateTo({
        url: '/pages/cunba/ranking/index'
      })
    },
    
    // 自定义导航栏切换事件
    onNavChange(navData) {
      console.log('导航栏切换:', navData)
      // 这里可以添加额外的逻辑，比如数据统计等
    },
    
    // 更新导航栏角标
    updateNavBadge(key, count) {
      this.navBadges[key] = count
    },
    
    // 清除指定导航项的角标
    clearNavBadge(key) {
      this.navBadges[key] = 0
    },
    
    // 模拟接收新消息/数据更新角标
    simulateDataUpdate() {
      // 模拟赛程更新
      setTimeout(() => {
        this.updateNavBadge('schedule', 5)
      }, 3000)
      
      // 模拟收到新消息
      setTimeout(() => {
        this.updateNavBadge('mine', 2)
      }, 5000)
    },
    
    // 演示API集成功能
    showNavDemo() {
      uni.showModal({
        title: 'API调试功能',
        content: '点击确定测试API连接\n\n将显示详细的调试信息\n帮助排查API问题',
        success: (res) => {
          if (res.confirm) {
            this.testApiConnection()
          }
        }
      })
    },
    
    // 测试API连接
    async testApiConnection() {
      uni.showLoading({ title: '测试API连接...' })
      
      try {
        console.log('=== API连接测试开始 ===')
        
        // 测试赛事列表API
        console.log('测试赛事列表API...')
        const eventResult = await getEventList()
        console.log('赛事列表响应:', eventResult)
        
        // 测试比赛列表API  
        console.log('测试比赛列表API...')
        const matchResult = await getMatchList({ limit: 5 })
        console.log('比赛列表响应:', matchResult)
        
        console.log('=== API连接测试完成 ===')
        
        uni.hideLoading()
        uni.showModal({
          title: 'API测试结果',
          content: `请查看控制台日志获取详细信息\n\n赛事API: ${eventResult ? '成功' : '失败'}\n比赛API: ${matchResult ? '成功' : '失败'}`,
          showCancel: false
        })
        
      } catch (error) {
        console.error('API测试失败:', error)
        uni.hideLoading()
        uni.showModal({
          title: 'API测试失败',
          content: `错误信息: ${error}\n\n请检查网络连接和API配置`,
          showCancel: false
        })
      }
    },
    
    // 页面滚动监听
    onPageScroll(e) {
      this.isPageScrolled = e.scrollTop > 0
    },
    
    // 下拉刷新
    async onPullDownRefresh() {
      try {
        await this.initData()
      } catch (error) {
        console.error('刷新失败:', error)
      } finally {
        uni.stopPullDownRefresh()
      }
    },


    
    // 获取轮播图链接
    getBannerLink(item) {
      if (item.link) return item.link
      if (item.url) return item.url
      if (item.href) return item.href
      return ''
    },

    
    // 查看球员详情（新增方法）
    viewPlayerDetail() {
      uni.navigateTo({
        url: '/pages/cunba/player_list/index'
      })
    },
    
    
    // 轮播图切换事件
    onBannerChange(event) {
      console.log('轮播图切换:', event.detail.current)
      // 可以在这里添加埋点统计
    },
    
    // 轮播图点击事件
    onBannerClick(banner) {
      console.log('点击轮播图:', banner)
      if (banner.link) {
        // 使用工具方法跳转页面（参考首页swiperBg组件）
        this.$util.JumpPath(banner.link)
      } else {
        // 默认行为，可以跳转到赛事详情或其他页面
        uni.showToast({
          title: banner.title,
          icon: 'none'
        })
      }
    },
    
    
    
    // 筛选组别数据（完全参考排行榜页面）
    filterGroupData(group) {
      console.log('=== 筛选组别数据 ===')
      console.log('当前组别:', group)
      console.log('总排行榜数据长度:', this.rankingData.length)
      console.log('总排行榜数据:', this.rankingData)
      
      if (!group || !this.rankingData.length) {
        console.log('⚠️ 组别或排行榜数据为空，设置空数组')
        this.currentGroupTeams = []
        return
      }
      
      // 根据组别名称筛选对应的球队数据
      const filteredTeams = this.rankingData.filter(team => {
        const match = team.group === group.name || team.groupName === group.name
        console.log(`球队 ${team.teamName || team.name} (组别: ${team.group || team.groupName}) 是否匹配组别 ${group.name}:`, match)
        return match
      })
      
      console.log('筛选后的球队数据:', filteredTeams)
      
      // 按排名排序
      this.currentGroupTeams = filteredTeams.sort((a, b) => {
        const rankA = a.rank || 999
        const rankB = b.rank || 999
        return rankA - rankB
      })
      
      console.log(`=== 组别 ${group.name} 最终球队数据 ===`)
      console.log('currentGroupTeams长度:', this.currentGroupTeams.length)
      console.log('currentGroupTeams详情:', this.currentGroupTeams)
      
      // 检查每个球队的ID字段
      this.currentGroupTeams.forEach((team, index) => {
        console.log(`球队${index + 1}:`, {
          id: team.id,
          teamId: team.teamId,
          name: team.name,
          teamName: team.teamName,
          group: team.group,
          groupName: team.groupName,
          originalData: team
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  background: #f5f5f5;
  min-height: 100vh;
}



/* 顶部轮播图横幅 */
.header-banner-swiper {
  position: relative;
  height: 200px;
  overflow: hidden;
  margin-top: 80px; /* 为自定义导航栏留出空间，确保最小88px */
  
  .banner-swiper {
    width: 100%;
    height: 100%;
    
    .swiper-item {
      width: 100%;
      height: 100%;
    }
    
    .banner-slide {
      position: relative;
      width: 100%;
      height: 100%;
      background-size: cover;
      background-position: center;
      background-repeat: no-repeat;
      display: flex;
      align-items: center;
      justify-content: center;
      
      // 默认渐变背景（当没有背景图时）
      background-image: linear-gradient(135deg, #00D4AA 0%, #4A90E2 100%);
    }
    
    .banner-overlay {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: linear-gradient(
        135deg,
        rgba(0, 0, 0, 0.3) 0%,
        rgba(0, 0, 0, 0.1) 50%,
        rgba(0, 0, 0, 0.3) 100%
      );
      z-index: 1;
    }
    
    .banner-content {
      position: relative;
      text-align: center;
      z-index: 2;
      padding: 0 20px;
      
      .banner-title {
        color: #fff;
        font-size: 24px;
        font-weight: bold;
        margin-bottom: 8px;
        text-shadow: 0 2px 8px rgba(0, 0, 0, 0.5);
      }
      
      .banner-subtitle {
        color: #fff;
        font-size: 16px;
        font-weight: 500;
        margin-bottom: 6px;
        text-shadow: 0 1px 4px rgba(0, 0, 0, 0.5);
      }
      
      .banner-description {
        color: rgba(255, 255, 255, 0.9);
        font-size: 14px;
        font-weight: 400;
        text-shadow: 0 1px 4px rgba(0, 0, 0, 0.5);
      }
    }
    
    .decoration-left {
      position: absolute;
      left: 20px;
      top: 50%;
      transform: translateY(-50%);
      z-index: 2;
      
      .basketball-icon {
        width: 60px;
        height: 60px;
        opacity: 0.4;
      }
    }
    
    .decoration-right {
      position: absolute;
      right: 20px;
      bottom: 20px;
      z-index: 2;
      
      .player-icon {
        width: 80px;
        height: 80px;
        opacity: 0.4;
      }
    }
  }
}

/* 通用section样式 */
.section {
  background: #fff;
  margin: 15px;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  .section-title {
    font-size: 18px;
    font-weight: bold;
    color: #333;
  }
  
  .section-more {
    font-size: 14px;
    color: #666;
  }
}

/* 近期赛事样式 */
.match-section {
  padding: 20px 0 !important;
  
  .section-header {
    padding: 0 20px;
    margin-bottom: 20px;
  }
}


/* 球队排名样式 */
.ranking-tabs {
  display: flex;
  margin-bottom: 20px;
  
  .tab-item {
    flex: 1;
    text-align: center;
    padding: 8px 12px;
    font-size: 14px;
    color: #666;
    border-bottom: 2px solid transparent;
    
    &.active {
      color: #4A90E2;
      border-bottom-color: #4A90E2;
      font-weight: bold;
    }
  }
}


/* 加载状态和空状态样式 */
.loading-state,
.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
}

.loading-text,
.empty-text {
  font-size: 14px;
  color: #999;
}

.loading-text::before {
  content: '⏳';
  margin-right: 8px;
  animation: loading-spin 1s linear infinite;
}

@keyframes loading-spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 页面容器样式 */
.page-with-cunba-nav {
  padding-bottom: calc(80px + env(safe-area-inset-bottom));
  padding-top: 0; /* 移除原有的顶部padding，使用导航栏组件的margin-top */
}

/* 禁用页面过渡动画 */
// #ifdef H5
.uni-page {
  transition: none !important;
  animation: none !important;
}
// #endif
</style>
